<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="器具名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入计量器具名称"
          clearable
          @keyup.enter.native="handleQuery"
          @change="getList"
        />
      </el-form-item>
      <el-form-item label="借用人员" prop="outPeople">
        <el-input
          v-model="queryParams.outPeople"
          placeholder="请输入借用人员名字"
          clearable
          @keyup.enter.native="handleQuery"
          @change="getList"
        />
      </el-form-item>
      <el-form-item label="借出时间" prop="outTime">
        <el-date-picker
          @change="getList"
          clearable
          v-model="queryParams.outTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择借出时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="归还时间" prop="returnTime" v-if="queryParams.isReturn===1">
        <el-date-picker
          @change="getList"
          clearable
          v-model="queryParams.returnTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择借出时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:records:add']"
        >借用器具</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:records:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:records:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordsList" @selection-change="handleSelectionChange" :cell-style="columnStyle">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id">
        <template slot-scope="scope">
          {{scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column label="器具编码" align="center" prop="instrumentsId" />
      <el-table-column label="器具名称" align="center" prop="name" />
      <el-table-column label="规格" align="center" prop="specification" />
      <el-table-column label="借出时间" align="center" prop="outTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.outTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="借用人" align="center" prop="outPeople" />
      <el-table-column label="班组" align="center" prop="group" />
      <el-table-column label="借出人" align="center" prop="lender" />
      <el-table-column label="是否归还" align="center" prop="isReturn">
        <template slot-scope="scope">
          <span v-if="scope.row.isReturn === 0">未归还</span>
          <span v-else>已归还</span>
        </template>
      </el-table-column>
      <el-table-column label="归还确认人" v-if="queryParams.isReturn===1" align="center" prop="returnConfirmPeople" width="100"/>
      <el-table-column label="归还时间" v-if="queryParams.isReturn===1" align="center" prop="returnTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="note" />
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width" v-if="$auth.hasPermi('system:records:remove') || queryParams.isReturn===0">
        <template slot-scope="scope">
          <el-button
            v-if="queryParams.isReturn===0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:records:edit']"
          >归还</el-button>
          <el-button
            v-if="queryParams.isReturn===1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:records:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改器具借用记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="85px">
        <el-form-item label="编码器具" prop="instrumentsId" @keydown.enter.native="instrumentsId">
          <el-input v-model="form.instrumentsId" :disabled="isUpdate" style="width: 350px;" ref="instrumentsId" placeholder="请扫描计量器具编码" clearable />
        </el-form-item>
        <el-form-item label="器具名称" prop="name"  v-if="isUpdate">
          <el-input v-model="form.name" :disabled="isUpdate" style="width: 350px;" ref="name" clearable />
        </el-form-item>
        <el-form-item label="借用人" prop="outPeople" @keydown.enter.native="inPeopleCode">
          <el-input v-model="form.outPeople"  style="width: 350px;margin-right: 10px;" :disabled="isUpdate || inPeopleDisabled" ref="outPeople" placeholder="请扫描借用人二维码" clearable />
          <el-button type="info" v-if="inPeopleDisabled" @click="reInPeople"  plain >重新录入</el-button>
        </el-form-item>
        <el-form-item label="班组" prop="group">
          <el-input v-model="form.group"  style="width: 350px;margin-right: 10px;" disabled placeholder="扫描借用人二维码自动获取" ref="group" clearable />
        </el-form-item>
        <el-form-item label="库房管理员" prop="lender">
          <el-input v-model="lender"  style="width: 350px;margin-right: 10px;" disabled  ref="lender"  placeholder="库房管理员名称自动获取" />
        </el-form-item>

        <el-form-item label="扫码归还" prop="outPeople" v-if="isUpdate" @keydown.enter.native="returnPeopleCode">
          <el-input v-model="form.returnPeople"  style="width: 350px;margin-right: 10px;" :disabled="inPeopleDisabled1" ref="returnPeople" placeholder="请扫描归还人人二维码" clearable />
          <el-button type="info" v-if="inPeopleDisabled1" @click="reInPeople1"  plain >重新录入</el-button>
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="form.note" style="width: 350px;" placeholder="请输入备注" clearable />
        </el-form-item>
        <el-table :data="outList" v-if="!isUpdate" @selection-change="handleSelectionChange">
          <el-table-column label="器具编码" align="center" prop="instrumentsId" />
          <el-table-column label="器具名称" align="center" prop="name" />
          <el-table-column label="规格" align="center" prop="specification" />
          <el-table-column label="检修时间" align="center" prop="repairTime" />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRecords,
  getRecords,
  delRecords,
  addRecords,
  updateRecords,
  getRecordsByInstrumentsId
} from '@/api/system/records'
import { getGoodsByMaterialId } from '@/api/system/goods'
import { getPeopleByCode } from '@/api/system/people'
import ScrollPane from '@/layout/components/TagsView/ScrollPane'
import { getUserProfile } from '@/api/system/user'

export default {
  name: "Records",
  components: { ScrollPane },
  data() {
    return {
      lender:'',
      returnConfirmPeople:'',
      returnOptions: [{
        value: 0,
        label: '未归还'
      }, {
        value: 1,
        label: '已归还'
      }],
      isUpdate:false,
      inPeopleDisabled:false,
      inPeopleDisabled1:false,
      // 借出单
      outList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 器具借用记录表格数据
      recordsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        instrumentsId: null,
        name: null,
        specification: null,
        outTime: null,
        outPeople: null,
        outNum: null,
        isReturn: null,
        returnTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // instrumentsId: [
        //   { required: true, message: "计量器具id不能为空", trigger: "blur" }
        // ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    columnStyle() {
      if(this.queryParams.isReturn === 0){
        return 'background:rgba(255,0,0,.1);'
      }
    },
    //扫描物料编码
    instrumentsId(e){
      let instrumentsId = e.target.value;
      let isAdd = false;
      this.outList.forEach((item)=>{
        if (instrumentsId === item.instrumentsId){
          this.$modal.msgError("该计量器具已扫过码！");
          this.form.instrumentsId = null;
          isAdd = true;
        }
      })
      if(isAdd){
        return;
      }
      //没有扫过码则查询具体信息
        getRecordsByInstrumentsId(instrumentsId).then(response=>{
          if(response.data !== undefined){
            if(response.data.inventory === 1){
              this.$modal.msgError("该计量器具已被借用,请先归还！")
              return;
            }
            this.outList.push(response.data);
          }else {
            this.$modal.msgError("没有此物料,请在基础数据库入库！")
          }
        })
      this.form.instrumentsId = null;
      // console.log(this.goodsInList);
    },
    //重新录入借用人员
    reInPeople(){
      this.inPeopleDisabled = false
      this.form.outPeople = null
      this.form.group = null
    },
    //重新录入归还人员
    reInPeople1(){
      this.inPeopleDisabled1 = false
      this.form.returnPeople = null
    },
    //扫描借用人员二维码
    inPeopleCode(e){
      let value = e.target.value;
      if (value === ''){
        return;
      }
      getPeopleByCode(value).then(response=>{
        if(response.data !== undefined){
          this.form.outPeople = response.data.name
          this.form.group = response.data.group
          this.inPeopleDisabled = true
        }else {
          this.$modal.msgError("没有此人员,请在人员基础数据库添加！")
        }
      })
    },
    //扫描归还人员二维码
    returnPeopleCode(e){
      let value = e.target.value;
      if (value === ''){
        return;
      }
      getPeopleByCode(value).then(response=>{
        if(response.data !== undefined){
          this.form.returnPeople = response.data.name
          this.inPeopleDisabled1 = true
        }else {
          this.$modal.msgError("没有此人员,请在人员基础数据库添加！")
          this.form.returnPeople = null
        }
      })
    },
    /** 查询器具借用记录列表 */
    getList() {
      if(this.$route.name === 'Return'){
        this.queryParams.isReturn = 1
      }else {
        this.queryParams.isReturn = 0

      }
      this.loading = true;
      listRecords(this.queryParams).then(response => {
        this.recordsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      getUserProfile().then(res=>{
        // console.log(res.data.nickName)
        this.lender = res.data.nickName
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.isUpdate = false
      this.inPeopleDisabled = false
      this.inPeopleDisabled1 = false
      this.outList = [];
      this.form = {
        id: null,
        instrumentsId: null,
        name: null,
        specification: null,
        outTime: null,
        outPeople: null,
        returnPeople:null,
        outNum: null,
        isReturn: null,
        returnTime: null,
        group: null,
        note: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "借用计量器具";
      //聚焦弹出框 因为弹窗绑定了键盘事件
      this.$nextTick(()=>{
        this.$refs.instrumentsId.focus()
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRecords(id).then(response => {
        this.form = response.data;
        this.isUpdate = true
        this.open = true;
        this.title = "归还计量器具";
        this.$nextTick(()=>{
          this.$refs.returnPeople.focus()
        })
      });

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        /** 归还器具 */
        if (valid) {
          if (this.form.id != null) {
            if(this.form.returnPeople === undefined || this.form.returnPeople === null || this.form.returnPeople === ''){
              this.$modal.msgError('归还人员不能为空哦!')
              return;
            }
            if(this.form.returnPeople !== this.form.outPeople){
              this.$modal.msgError('借用人员与归还人员不一致!')
              return;
            }
            //记录归还时间
            let goodsInTime = new Date()
            this.form.returnTime = goodsInTime
            this.form.returnConfirmPeople = this.lender
            updateRecords(this.form).then(response => {
              this.$modal.msgSuccess("归还成功");
              this.open = false;
              this.getList();
            });

            /** 借用器具 */
          } else {
            if (this.outList.length === 0){
              this.$modal.msgError('器具借用单不能为空哦!')
              return;
            }
            if(this.form.outPeople === undefined ||this.form.outPeople === null || this.form.outPeople === ''){
              this.$modal.msgError('借用人员不能为空哦!')
              return;
            }
            //记录出库时间
            let goodsInTime = new Date();
            // console.log(parseTime(goodsInTime, '{y}-{m}-{d} {h}:{i}'))
            // console.log(goodsInTime)
            this.outList.forEach((item)=>{
              item.outTime = goodsInTime;
              item.outPeople = this.form.outPeople;
              item.group = this.form.group;
              item.isReturn = 0;
              item.lender = this.lender;
              item.note = this.form.note;
            })
            addRecords(this.outList).then(response => {
              this.$modal.msgSuccess("借用成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除器具借用记录编号为"' + ids + '"的数据项？').then(function() {
        return delRecords(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/records/export', {
        ...this.queryParams
      }, `records_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped="scoped">
/*更改表格每行背景颜色*/
/*/deep/.el-table__body tbody tr>td {*/
/*  background-color: rgba(255,0,0,.1);*/
/*}*/
</style>
